<template>
  <div class="app-container">
    <el-form size="small" inline>
      <el-form-item label="承包代表">
        <el-input v-model="query.contractorDeputy" placeholder="请输入身份证号" clearable />
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="query.idcardNumber" placeholder="请输入身份证号" clearable />
      </el-form-item>
      <el-form-item label="所属组织">
        <agriculture-region :value.sync="query.deptId" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
        <el-button plain icon="el-icon-refresh" @click="handleReset"> 重置</el-button>
        <el-button plain icon="el-icon-plus" type="success" @click="addDialogVisible = true">新增</el-button>
        <el-button plain icon="el-icon-download" type="warning" @click="handleExport">导出</el-button>
        <el-button plain icon="el-icon-upload2" type="danger" @click="uploadDialogVisible = true">导入</el-button>
        <help></help>
      </el-form-item>
    </el-form>
    <el-table border v-loading="loading" :data="list">
      <el-table-column align="center" label="承包方名称" prop="contractorDeputy" min-width="80" />
      <el-table-column align="center" label="身份证号" prop="idcardNumber" min-width="150" show-overflow-tooltip />
      <el-table-column align="center" label="联系方式" prop="cellPhone" min-width="120" />
      <el-table-column align="center" label="联系人" prop="linkMan" min-width="80" />
      <el-table-column align="center" label="联系方式" prop="linkPhone" min-width="120" />
      <el-table-column align="center" label="所属组织" show-overflow-tooltip>
        <template slot-scope="scope">
          <agriculture-region :value.sync="scope.row.deptId" type="text" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="承包土地总数" prop="landTotal" min-width="120" />
      <el-table-column align="center" label="承包地确权总面积" min-width="140">
        <template slot-scope="scope">
          {{ Number(scope.row.landArea).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-document" @click="contractorInfo(scope.row.contractorId)"
            >详情
          </el-button>
          <el-button type="text" size="small" icon="el-icon-edit" @click="updateContractor(scope.row.contractorId)"
            >编辑
          </el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="deleteContractor(scope.row.contractorId)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />
    <help-dialog title="承包新增" :visible.sync="addDialogVisible" @close="dialogClose">
      <el-form size="small" label-width="140px" ref="form" :model="queryParam" :rules="rules">
        <div class="label">承包方信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="承包方名称" prop="contractorDeputy">
              <el-input v-model="queryParam.contractorDeputy" placeholder="请输入承包方名称" clearable />
            </el-form-item>
            <el-form-item label="承包方联系方式" prop="cellPhone">
              <el-input v-model="queryParam.cellPhone" maxlength="11" placeholder="请输入联系方式" clearable />
            </el-form-item>
            <el-form-item label="联系人" prop="linkMan">
              <el-input v-model="queryParam.linkMan" placeholder="请输入联系人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idcardNumber">
              <el-input v-model="queryParam.idcardNumber" placeholder="请输入身份证号" maxlength="18" clearable />
            </el-form-item>
            <el-form-item label="联系人联系方式" prop="linkPhone">
              <el-input v-model="queryParam.linkPhone" maxlength="11" placeholder="请输入联系人联系方式" clearable />
            </el-form-item>
            <el-form-item label="所属组织" prop="deptId">
              <agriculture-region :value.sync="queryParam.deptId" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="label">家庭成员情况</div>
        <family ref="family" @submit="familySubmit" :list="info.family"></family>
        <div class="label">土地详情</div>
        <land ref="land" @submit="landSubmit" :list="info.list"></land>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button v-if="queryParam.contractorId" type="primary" @click="handleUpload">更 新</el-button>
        <el-button v-else type="primary" @click="addContractor">确 定</el-button>
      </span>
    </help-dialog>

    <help-dialog title="承包详情" :visible.sync="infoDialogVisible">
      <el-descriptions title="土地基本信息">
        <el-descriptions-item label="承包方名称">{{ info.contractorDeputy }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ info.idcardNumber }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ info.cellPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ info.linkMan }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ info.linkPhone }}</el-descriptions-item>
        <el-descriptions-item label="所属组织">
          <agriculture-region :value.sync="info.deptId" type="text" />
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        v-for="(item, index) in info.family"
        :key="index"
        :title="`家庭成员情况${index + 1}`"
        :column="3"
      >
        <el-descriptions-item label="姓名">{{ item.name }}</el-descriptions-item>
        <el-descriptions-item label="与承包方名称关系">{{ item.relation }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ item.remark }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="承包土地情况">
        <el-descriptions-item label="承包土地总数">{{ info.landTotal }}</el-descriptions-item>
        <el-descriptions-item label="承包地确权总面积">{{ Number(info.landArea).toFixed(2) }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-for="(v, index) in info.list" :key="v.landId" :title="`土地详情${index + 1}`" :column="3">
        <el-descriptions-item label="土地编码/地宗号">{{ v.landCode }}</el-descriptions-item>
        <el-descriptions-item label="坐落（四至）"
          >东至{{ v.east }}西至{{ v.west }}南至{{ v.south }}北至{{ v.north }}
        </el-descriptions-item>
        <el-descriptions-item label="面积（亩）">{{ v.area }}</el-descriptions-item>
        <el-descriptions-item label="是否农田">
          <dict-tag :options="dict.type.agriculture_basic_land" :value="v.basicLand" />
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ v.remark }}</el-descriptions-item>
        <el-descriptions-item label="承包期限">{{ v.deadline }}</el-descriptions-item>
        <el-descriptions-item label="权证附件">
          <y-show-all-file :path="v.file" height="50px" width="50px" />
        </el-descriptions-item>
      </el-descriptions>
    </help-dialog>

    <help-dialog
      title="承包管理导入"
      :visible.sync="uploadDialogVisible"
      width="30%"
      align="center"
      @close="closeUpload"
    >
      <el-upload class="upload-demo" drag action="#" :http-request="imported" multiple ref="upload" accept=".xlsx,.xls">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx、xls文件，且不超过500kb</div>
      </el-upload>
      <el-button type="text" @click="templateDownload">承包管理导入模版</el-button>
    </help-dialog>
  </div>
</template>

<script>
import contractorApi from '@/api/contractor/contractor'
import Family from '@/views/contractor/contractor/components/Family'
import Land from '@/views/contractor/contractor/components/Land'
import AgricultureRegion from '@/components/AgricultureRegion/AgricultureRegion'

export default {
  dicts: ['agriculture_organization', 'agriculture_basic_land'],
  components: { Family, Land, AgricultureRegion },
  data() {
    return {
      loading: false,
      list: [],
      query: {
        contractorDeputy: '',
        idcardNumber: '',
        deptId: '',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      addDialogVisible: false,
      uploadDialogVisible: false,
      infoDialogVisible: false,
      queryParam: {
        contractorDeputy: '',
        idcardNumber: '',
        cellPhone: '',
        linkMan: '',
        deptId: '',
        contractorType: '',
        linkPhone: '',
        list: []
      },
      rules: {
        contractorDeputy: [{ required: true, message: '请输入承包方名称', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择所属组织', trigger: 'blur' }]
      },
      info: {
        family: [],
        list: []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      contractorApi.getContractorData(this.query).then((res) => {
        this.list = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    handleReset() {
      this.query = {
        contractorDeputy: '',
        idcardNumber: '',
        deptId: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },
    handleExport() {
      this.download(
        '/agriculture/contractor/export',
        {
          ...this.query
        },
        `承包管理_${new Date().getTime()}.xlsx`
      )
    },
    imported(item) {
      var formData = new FormData()
      formData.append('file', item.file)
      contractorApi.importContractorData(formData).then((res) => {
        this.$message.success('导入成功')
        this.closeUpload()
        this.getList()
      })
    },
    closeUpload() {
      this.$refs.upload.clearFiles()
      this.uploadDialogVisible = false
    },
    dialogClose() {
      this.addDialogVisible = false
      this.queryParam = {
        contractorDeputy: '',
        idcardNumber: '',
        cellPhone: '',
        linkMan: '',
        deptId: '',
        contractorType: '',
        linkPhone: '',
        list: []
      }

      this.$refs.family.clearValidate()
      this.$refs.land.clearValidate()
      this.$refs.form.clearValidate()

      this.$refs.family.obj = {
        family: [{ name: null, relation: null, remark: null }]
      }
      this.$refs.land.obj = {
        landDetail: [
          {
            landCode: '',
            area: '',
            east: '',
            south: '',
            west: '',
            north: '',
            remark: '',
            deadline: '',
            file: ''
          }
        ]
      }
    },
    familySubmit(val) {
      this.queryParam.family = JSON.stringify(val)
    },
    landSubmit(val) {
      this.queryParam.list = val
    },
    addContractor() {
      this.$refs.family.submit()
      if (!this.queryParam.family) {
        return
      }

      this.$refs.land.submit()
      this.$nextTick(() => {
        if (this.queryParam.list.length == 0) {
          return
        }
        this.$refs.form.validate((valid) => {
          if (valid) {
            contractorApi.addContractor(this.queryParam).then((res) => {
              this.$message.success('添加成功')
              this.dialogClose()
              this.getList()
            })
          } else {
            return false
          }
        })
      })
    },
    contractorInfo(contractorId) {
      contractorApi.detailContractor({ contractorId: contractorId }).then((res) => {
        res.data.family = JSON.parse(res.data.family)
        this.info = res.data
        this.infoDialogVisible = true
      })
    },
    templateDownload() {
      download('/profile/upload/2023/5/29/temp_fd718c23febf4561b9c9e2b1ebbece7c.xls')
    },
    async updateContractor(contractorId) {
      const val = await contractorApi.detailContractor({ contractorId: contractorId })
      const {
        data: { list, family }
      } = val
      list.map((item) => (item.disabled = true))
      this.info.list = list

      this.info.family = JSON.parse(family)
      this.queryParam = {
        contractorDeputy: val.data.contractorDeputy,
        idcardNumber: val.data.idcardNumber,
        cellPhone: val.data.cellPhone,
        linkMan: val.data.linkMan,
        deptId: val.data.deptId,
        contractorType: val.data.contractorType,
        linkPhone: val.data.linkPhone,
        list: [],
        contractorId: contractorId
      }
      this.addDialogVisible = true

      this.$nextTick(() => {
        this.$refs.land.getFileShow()
      })
    },
    handleUpload() {
      this.$refs.family.submit()
      if (!this.queryParam.family) {
        return
      }

      this.$refs.land.submit()
      if (this.queryParam.list.length == 0) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          contractorApi.updateContractor(this.queryParam).then((res) => {
            this.$message.success('修改成功')
            this.dialogClose()
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    deleteContractor(contractorId) {
      this.$confirm('确认删除当前承包?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          contractorApi.deleteContractor({ contractorId: contractorId }).then((res) => {
            this.$message.success('删除成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    }
  }
}
</script>

<style scoped>
.label {
  font-size: 16px;
  font-weight: 700;
  color: #409eff;
  margin: 20px 0;
  border-left: 3px solid;
  padding-left: 5px;
  line-height: 20px;
}

/deep/ .el-descriptions__body .el-descriptions__table {
  white-space: nowrap;
}

/deep/ .el-descriptions-item__content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 8px;
}
</style>